package com.watson.nettydemo.demo08;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * SimpleChannelInboundHandler 与 ChannelInboundHandlerAdapter 的区别，，SimpleChannelInboundHandler会将消息自动释放
 *
 * @author: llun
 * @date: 2022/3/11 14:54
 * @version: 1.0
 */
public class IdeSocketServerHandler extends ChannelInboundHandlerAdapter {
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
       //
        if (evt instanceof IdleStateEvent) {
            String state = "";
            IdleStateEvent stateEvent = (IdleStateEvent) evt;
            switch (stateEvent.state()) {
                case READER_IDLE:
                    state = "读超时";
                    break;
                case WRITER_IDLE:
                    state = "写超时";
                    break;
                default:
                    ALL_IDLE:
                    state = "读写超时";
            }
            System.out.println(state);

            // 关闭连接
            ctx.close();
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
